package com.macro.mall.controller.ums;

import com.github.pagehelper.Page;
import com.macro.mall.commission.entity.UserAccountEntity;
import com.macro.mall.commission.service.OrderPredicateService;
import com.macro.mall.commission.service.UserAccountService;
import com.macro.mall.common.api.CommonPage;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.common.api.exception.BusinessException;
import com.macro.mall.common.api.util.BigDecimalUtils;
import com.macro.mall.common.api.util.LocalDateTimeUtils;
import com.macro.mall.dto.ums.PagedQueryMemberReqDto;
import com.macro.mall.dto.ums.UpdateBefIdReqDto;
import com.macro.mall.dto.ums.UpdateMemberReqDto;
import com.macro.mall.ums.domain.Member;
import com.macro.mall.ums.entity.MemberEntity;
import com.macro.mall.ums.service.account.MemberService;
import com.macro.mall.ums.service.account.bo.PagedQueryMemberInput;
import com.macro.mall.ums.service.account.bo.UpdateMemberInput;
import com.macro.mall.vo.account.AccountVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 会员控制器
 *
 * @author xuyanjun
 * @date 2020-01-04
 */
@Api(tags = "会员")
@Slf4j(topic = "MemberController")
@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private MemberService memberService;

    @Autowired
    private UserAccountService userAccountService;

    @Autowired
    private OrderPredicateService orderPredicateService;

    /**
     * 修改会员
     *
     * @param reqDto reqDto
     * @return 会员
     */
    @ApiOperation("修改会员")
    @PostMapping("update")
    public CommonResult<Member> update(@RequestBody UpdateMemberReqDto reqDto) {
        UpdateMemberInput updateMemberInput = new UpdateMemberInput();
        updateMemberInput
                .setId(reqDto.getId())
                .setNickname(reqDto.getNickname())
                .setPhone(reqDto.getPhone())
                .setStatus(reqDto.getStatus())
                .setIcon(reqDto.getIcon())
                .setGender(reqDto.getGender())
                .setBirthday(reqDto.getBirthday())
                .setCity(reqDto.getCity())
                .setJob(reqDto.getJob())
                .setPersonalizedSignature(reqDto.getPersonalizedSignature())
                .setSourceType(reqDto.getSourceType())
                .setIntegration(reqDto.getIntegration())
                .setGrowth(reqDto.getGrowth())
                .setLuckeyCount(reqDto.getLuckeyCount())
                .setHistoryIntegration(reqDto.getHistoryIntegration())
                .setLevel(reqDto.getLevel())
                .setInvitationCode(reqDto.getInvitationCode());

        memberService.update(updateMemberInput);

        MemberEntity memberEntity = memberService.getById(reqDto.getId());
        Member member = memberService.entityToDomain(memberEntity);

        return CommonResult.success(member);
    }

    /**
     * 修改会员上级id
     *
     * @param reqDto reqDto
     * @return 会员
     */
    @ApiOperation("修改会员上级id")
    @PostMapping("updateBefId")
    public CommonResult updateBefId(@RequestBody UpdateBefIdReqDto reqDto) {
        memberService.updateBefId(reqDto.getId(), reqDto.getBefId());

        return CommonResult.success(null);
    }

    /**
     * 分页查询会员
     *
     * @return 分页后的会员
     */
    @ApiOperation("分页查询会员")
    @PostMapping("pagedQuery")
    public CommonPage<Member> pagedQuery(@RequestBody PagedQueryMemberReqDto reqDto) {
        PagedQueryMemberInput pagedQueryMemberInput = new PagedQueryMemberInput();
        pagedQueryMemberInput
                .setUserId(reqDto.getId())
                .setBefId(reqDto.getBefId())
                .setLevel(reqDto.getLevel())
                .setPhone(reqDto.getPhone())
                .setNickname(reqDto.getNickname())
                .setPageIndex(reqDto.getPageIndex())
                .setPageSize(reqDto.getPageSize());

        Page<MemberEntity> pageInfo = memberService.pagedQuery(pagedQueryMemberInput);
        List<Member> members = memberService.entityToDomain(pageInfo);

        return CommonPage.restPage(members, pageInfo);
    }

    /**
     * 根据id获取会员
     *
     * @param id id
     * @return 会员
     */
    @ApiOperation("根据id获取会员")
    @GetMapping("{id}")
    public CommonResult<Member> getById(@PathVariable long id) {
        if (id <= 0) {
            throw new BusinessException("要获取的会员Id不能为空。");
        }

        MemberEntity memberEntity = memberService.getById(id);
        if (memberEntity == null) {
            throw new BusinessException(String.format("要获取的会员id:%s不存在。", id));
        }

        Member member = memberService.entityToDomain(memberEntity);

        return CommonResult.success(member);
    }

    /**
     * 根据批量id获取会员
     *
     * @param ids ids
     * @return 会员
     */
    @ApiOperation("根据批量id获取会员")
    @PostMapping("listByBatchIds")
    public CommonResult<List<Member>> listByBatchIds(@RequestBody List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("要获取的会员Id集合不能为空。");
        }

        List<MemberEntity> memberEntities = memberService.listByBatchIds(ids);
        List<Member> members = memberService.entityToDomain(memberEntities);

        return CommonResult.success(members);
    }

    /**
     * 获取当前会员统计信息
     */
    @ApiOperation("获取当前会员统计信息")
    @PreAuthorize("isAuthenticated()")
    @GetMapping(value = "/account/{id}")
    public CommonResult<AccountVO> getAccountByMemberId(@PathVariable(name = "id") Long id) {
        AccountVO accountVO = new AccountVO();
        setPredictCommission(id, accountVO);

        return CommonResult.success(accountVO);
    }


    /**
     * 设置预估佣金
     *
     * @param myVo myVo
     */
    private void setPredictCommission(long userId, AccountVO myVo) {
        UserAccountEntity userAccountEntity = userAccountService.getByUserId(userId);

//        // 今日预估
//        LocalDateTime minTimeOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MIN);
//        LocalDateTime maxTimeOfToday = LocalDateTime.of(LocalDate.now(), LocalTime.MAX);
//
//        long predictOfToday = orderPredicateService.sumAmountByCreateTimeOfUser(userId, minTimeOfToday, maxTimeOfToday);
//        myVo.setPredictOfToday(BigDecimalUtils.fromFengToYuan((int) predictOfToday, 2).toString());
//
//        // 昨日预估
//        LocalDateTime minTimeOfYesterday = minTimeOfToday.plusDays(-1);
//        LocalDateTime maxTimeOfYesterday = maxTimeOfToday.plusDays(-1);
//
//        long predictOfYesterday = orderPredicateService.sumAmountByCreateTimeOfUser(userId, minTimeOfYesterday, maxTimeOfYesterday);
//        myVo.setPredictOfYesterday(BigDecimalUtils.fromFengToYuan((int) predictOfYesterday, 2).toString());

        // 本月预估
        LocalDateTime minTimeOfThisMonth = LocalDateTimeUtils.getFirstDateOfMonth(LocalDateTime.now());
        LocalDateTime maxTimeOfThisMonth = LocalDateTimeUtils.getLastDateOfMonth(LocalDateTime.now());

        long predictOfThisMonth = orderPredicateService.sumAmountByCreateTimeOfUser(userId, minTimeOfThisMonth, maxTimeOfThisMonth);
        myVo.setPredictOfThisMonth(BigDecimalUtils.fromFengToYuan((int) predictOfThisMonth, 2).toString());

        // 总预估
        long predictOfTotal = userAccountEntity == null ? 0 : userAccountEntity.getTotal();
        myVo.setPredictOfTotal(BigDecimalUtils.fromFengToYuan((int) predictOfTotal, 2).toString());

        // 账户余额
        int balance = userAccountEntity == null ? 0 : userAccountEntity.getBalance();
        myVo.setBalance(BigDecimalUtils.fromFengToYuan(balance, 2).toString());
    }

}

